//
//  BottomPlayView.m
//  Kugou-OC
//
//  Created by BH on 16/4/5.
//  Copyright © 2016年 Sunny. All rights reserved.
//

#import "BottomPlayView.h"
#import "GlobalDefine.h"
#import "MusicInfoModel.h"
#import "PlayHelper.h"
#import "NSTimer+Control.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import <SDAutoLayout/UIView+SDAutoLayout.h>
#import <SDWebImage/UIImageView+WebCache.h>

#define Margin 10

@interface BottomPlayView ()

@property(nonatomic,strong)UIButton *nextBtn;//切换下一首
@property(nonatomic,strong)UIButton *playListBtn;//显示播放列表

@end

@implementation BottomPlayView

+(instancetype)shareBottomView{
    static BottomPlayView *bottomView = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        bottomView = [[self alloc] init];
    });
    return bottomView;
}

-(NSInteger)currentPlayIndex{
    if (!_currentPlayIndex) {
        self.currentPlayIndex = 0;
    }
    
    return _currentPlayIndex;
}

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        //背景
        UIImageView *bgImgV = [[UIImageView alloc] init];
        bgImgV.image = IMAGE(@"bottom_background");
        
        //初始化
        _iconImg = [[UIImageView alloc] init];
        _silder = [[UISlider alloc] init];
        _singNameLab = [[UILabel alloc] init];
        _singerLab = [[UILabel alloc] init];
        _playBtn = [[UIButton alloc] init];
        _nextBtn = [[UIButton alloc] init];
        _playListBtn = [[UIButton alloc] init];
        
        //添加subview
        [self sd_addSubviews:@[bgImgV,_iconImg,_silder,_singNameLab,_singerLab,_playBtn,_nextBtn,_playListBtn]];
        
        bgImgV.sd_layout
        .leftEqualToView(self)
        .topSpaceToView(self,0)
        .rightEqualToView(self)
        .bottomEqualToView(self);
        //单击bottomview显示播放界面
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
            [self addGestureRecognizer:tap];
        
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    //图标
    _iconImg.sd_layout
    .leftSpaceToView(self,Margin)
    .bottomSpaceToView(self,6)
    .heightIs(60)
    .widthEqualToHeight();
    
    //歌曲进度
    _silder.minimumValue = 0.0;
    _silder.minimumTrackTintColor = COLOR(44, 120, 218, 1);
    _silder.maximumTrackTintColor = [UIColor lightGrayColor];
    [_silder setThumbImage:IMAGE(@"bottom_slider_thumbImage") forState:UIControlStateNormal];
    _silder.sd_layout
    .leftSpaceToView(_iconImg,Margin)
    .topSpaceToView(self,18)
    .rightSpaceToView(self,Margin)
    .heightIs(15);
    [_silder addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [_silder addTarget:self action:@selector(sliderDragDone:) forControlEvents:UIControlEventTouchUpInside];
    
    //显示播放列表按钮
    [_playListBtn setBackgroundImage:IMAGE(@"bottom_playlist") forState:UIControlStateNormal];
    _playListBtn.sd_layout
    .topSpaceToView(_silder,Margin/2)
    .rightEqualToView(_silder)
    .bottomSpaceToView(self,Margin)
    .widthIs(35);
    _playListBtn.tag = 102;
    [_playListBtn addTarget:self action:@selector(bottomViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //下一曲按钮
    [_nextBtn setImage:IMAGE(@"bottom_next") forState:UIControlStateNormal];
    _nextBtn.sd_layout
    .rightSpaceToView(_playListBtn,Margin/2)
    .topEqualToView(_playListBtn)
    .widthIs(_playListBtn.width)
    .bottomEqualToView(_playListBtn);
    _nextBtn.tag = 101;
    [_nextBtn addTarget:self action:@selector(bottomViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //播放or暂停按钮
    _playBtn.sd_layout
    .rightSpaceToView(_nextBtn,Margin/2)
    .topEqualToView(_nextBtn)
    .bottomEqualToView(_nextBtn)
    .widthIs(_nextBtn.width);
    _playBtn.tag = 100;
    [_playBtn setImage:IMAGE(@"bottom_pause") forState:UIControlStateNormal];
    [_playBtn addTarget:self action:@selector(bottomViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //歌曲名
    _singNameLab.font = TITLE_THIRD_FONT;
    _singNameLab.sd_layout
    .rightSpaceToView(_playBtn,Margin)
    .topSpaceToView(_silder,0)
    .leftSpaceToView(_iconImg,Margin)
    .heightIs(22);
    
    //歌手
    _singerLab.font = TITLE_FOUR_FONT;
    _singerLab.textColor = TITLE_FOUR_TEXT_COLOR;
    _singerLab.sd_layout
    .leftEqualToView(_singNameLab)
    .topSpaceToView(_singNameLab,0)
    .widthIs(_singNameLab.width)
    .bottomEqualToView(_iconImg);
    
    MusicInfoModel *model = _musicList[_currentPlayIndex];
    if (model) {
        //歌曲名
        _singNameLab.text = model.music_name;
        //歌手
        _singerLab.text = model.music_artist;
        //歌曲icon
        [_iconImg sd_setImageWithURL:[NSURL URLWithString:model.music_icon] placeholderImage:IMAGE(@"bottom_placeholder_image")];
    }else{
        _singNameLab.text = @"歌曲名";
        _singerLab.text = @"歌手名";
        _iconImg.image = IMAGE(@"bottom_placeholder_image");
    }
}

//获取播放列表
-(void)setMusicList:(NSArray *)musicList{
    _musicList = musicList;
}

//单击bottomview显示播放界面
-(void)handleTap:(id)sender{
    
    if (self.TapBottomView) {
        self.TapBottomView(_musicList,_currentPlayer,_currentPlayIndex);
    }
}

//按钮点击
-(void)bottomViewBtnClick:(UIButton *)button{
    
    PlayHelper *playHelper = [PlayHelper sharePlayHelper];
    BOOL isplaying = [USERDEFAULT boolForKey:@"isPlaying"];
    button.selected = !button.selected;
    //是否正在播放歌曲
    if (button.tag==100) {
        if (_silder.value==0) {
            [self setupPlayerWithModel:_musicList[_currentPlayIndex]];
        }
        
        //播放或暂停
        if (isplaying) {
            //暂停
            [playHelper.aPlayer pause];
            [_playerTimer pauseTimer];
            [_playBtn setImage:IMAGE(@"bottom_pause") forState:UIControlStateNormal];

        }else{
            //播放
            [playHelper.aPlayer play];
            [_playerTimer resumeTimer];
            [_playBtn setImage:IMAGE(@"bottom_play") forState:UIControlStateNormal];

        }
    
        [USERDEFAULT setBool:!isplaying forKey:@"isPlaying"];
    }else if (button.tag == 101){
        //切换下一首
        //如果当前播放不存在，则返回
        if (!_currentPlayer) {
            return;
        }
        //当前列表只有一首歌
        if (_musicList.count == 1) {
            MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.superview animated:YES];
            mb.mode = MBProgressHUDModeText;
            mb.labelText = @"-.-只有一首歌";
            [mb hide:YES afterDelay:0.5];
            return;
        }
        //播放下一首
        [self nextSong];
    }else{
        
        //显示播放列表
        if ([self.delegate respondsToSelector:@selector(showPlayListViewWithItem:array:index:hidden:)]) {
            [self.delegate showPlayListViewWithItem:_currentPlayer array:_musicList index:_currentPlayIndex hidden:!button.selected];
        }
    }
}

/**
 *  设置当前播放歌曲
 *
 *  @param model 播放歌曲model
 */
-(void)setupPlayerWithModel:(MusicInfoModel *)model{
    //歌曲名
    _singNameLab.text = model.music_name;
    //歌手
    _singerLab.text = model.music_artist;
    //歌曲icon
    if ([model.music_icon isEqualToString:@""]) {
        _iconImg.image = IMAGE(@"bottom_placeholder_image");
    }
    [_iconImg sd_setImageWithURL:[NSURL URLWithString:model.music_icon] placeholderImage:IMAGE(@"bottom_placeholder_image")];
    
    //歌曲url
    if (model.music_source == kMusicSourceLocal) {
        NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"LocalMusic" ofType:@"bundle"];
        NSBundle *subBundle = [NSBundle bundleWithPath:bundlePath];
        NSString *path = [subBundle pathForResource:[NSString stringWithFormat:@"%@-%@",model.music_artist,model.music_name] ofType:model.music_type];
        self.playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:path]];
        
    }else{
        NSString *path = [NSString stringWithFormat:@"%@/%@-%@.%@",CACHE_DIRECTORY,model.music_artist,model.music_name,model.music_extname];
        self.playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:path]];
    }
    
    //添加通知：播放完成后调用
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemAction:) name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
    
    //播放音乐
    PlayHelper *playHelper = [PlayHelper sharePlayHelper];
    [playHelper.aPlayer replaceCurrentItemWithPlayerItem:_playerItem];
    [USERDEFAULT setBool:YES forKey:@"isPlaying"];
    [playHelper.aPlayer play];
    [_playBtn setImage:IMAGE(@"bottom_play") forState:UIControlStateNormal];
    
    //添加计时器
    if (self.playerTimer) {
        [self.playerTimer invalidate];
    }
    self.playerTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(handleTimeAction:) userInfo:_playerItem repeats:YES];
    
}

/**
 *  歌曲播放完后处理事件
 */
-(void)playerItemAction:(AVPlayerItem *)item{
    [self.playerTimer invalidate];
    
    if (self.NextSong) {
        
        self.NextSong();
        
    }else{
        //给系统一个延迟，准备播放下一首
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_playBtn setImage:IMAGE(@"bottom_pause") forState:UIControlStateNormal];
            [self nextSong];
        });
    }
}

/**
 *  计时器-进度条
 */
-(void)handleTimeAction:(NSTimer *)timer{
    AVPlayerItem *newPlayer = (AVPlayerItem*)timer.userInfo;
    if ([newPlayer status] == AVPlayerStatusReadyToPlay) {
        //当播放时，存储当前播放的Item， 用来与播放界面之间的信息通讯
        _currentPlayer = newPlayer;
        if (self.ASTimer) {
            self.ASTimer(newPlayer);
        }
    }

    CMTime duration = _playerItem.asset.duration;
    _silder.maximumValue = CMTimeGetSeconds(duration);
    _silder.value = CMTimeGetSeconds(_playerItem.currentTime);
}

/**
 *  播放下一首
 */
-(void)nextSong{
    _currentPlayIndex++;
    [BottomPlayView shareBottomView].playerItem = nil;
    [_playBtn setImage:IMAGE(@"bottom_play") forState:UIControlStateNormal];
    
//    //判断缓存中是否存在当前文件
    MusicInfoModel *model = self.musicList[_currentPlayIndex];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *finalPath = [CACHE_DIRECTORY stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%@.%@",model.music_artist,model.music_name,model.music_extname]];
    if (![fileManager fileExistsAtPath:finalPath] && model.music_source == kMusicSourceNetwork) {
        /*
        //获取音乐下载地址
        NSDictionary *params = @{@"hash":model.music_hash,@"cmd":@"playInfo"};
        
        [[PlayHelper sharePlayHelper] getMusicUrlWithParam:params method:@"sync" success:^(id JSON) {
            NSString *downloadUrl = JSON[@"url"];
            
            [[PlayHelper sharePlayHelper] downloadMusicWithUrl:downloadUrl method:@"sync" param:nil filename:[NSString stringWithFormat:@"%@-%@.%@",model.music_artist,model.music_name,model.music_extname] success:^(id JSON) {
                [self setupPlayerWithModel:model];
            } failure:^(NSError *error) {
                
            }];
            
        } failure:^(NSError *error) {
            
        }];
        */
    }else{
        if (_currentPlayIndex >= _musicList.count) {
            _currentPlayIndex = 0;
            [self setupPlayerWithModel:[_musicList firstObject]];
        }else{
            [self setupPlayerWithModel:_musicList[_currentPlayIndex]];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PlayerItemDidPlayToEndTime" object:@(_currentPlayIndex)];
    }
}

/**
 *  拖动滑块
 */
-(void)sliderValueChanged:(UISlider *)sender{
    //如果当前播放不存在，则返回
    if (!_currentPlayer) {
        return;
    }
    //暂停计时
    [self.playerTimer pauseTimer];
}

/**
 *  拖动结束
 */
-(void)sliderDragDone:(UISlider *)sender{
    if (!_currentPlayer) {
        _silder.value = 0;
        return;
    }
    //开始计时
    [self.playerTimer resumeTimer];
    _silder.value = sender.value;
    
    CMTime dragedCMTime = CMTimeMake(sender.value, 1);
    [[PlayHelper sharePlayHelper].aPlayer pause];
    [[PlayHelper sharePlayHelper].aPlayer seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
        [[PlayHelper sharePlayHelper].aPlayer play];
    }];
}

@end
